const app = getApp()
const db = wx.cloud.database()
const _ = db.command

Page({
  onLoad() {
    wx.cloud.init()
    this.ctx = wx.createCameraContext()
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        this.openid = res.result.openid
      },
      fail: err => {
        console.error(err)
      }
    })
  },
  onTapEntry() {
    var tempInagePath
    var fileID
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        })
        wx.showLoading({
          title: '验证中...',
          mask: true
        })
        this.tempImagePath = res.tempImagePath
        var random = Date.parse(new Date()) + Math.ceil(Math.random() * 1000)
        var uploadTask = wx.cloud.uploadFile({
          cloudPath: this.openid + '' + random + '.png',
          filePath: res.tempImagePath,
          success: res => {
            console.log(res.fileID)
            this.fileID = res.fileID
            wx.cloud.callFunction({
              name: 'Face_Detection',
              data: {
                fileID: this.fileID
              },
              success: res => {
                wx.cloud.callFunction({
                  name: 'Add_Person',
                  data: {
                    "groupid": "public",
                    "personname": this.openid,
                    "personid": this.openid,
                    "fileID": this.fileID
                  },
                  success: res => {
                    db.collection('verifiedperson').add({
                        // data 字段表示需新增的 JSON 数据
                        data: {
                          _userid: this.openid
                        }
                      })
                      .then(res => {
                        console.log(res)
                        wx.hideLoading()
                        wx.showToast({
                          title: '成功',
                          mask: true,
                          icon: 'success',
                          duration: 1000
                        })
                        setTimeout(function () {
                          wx.navigateBack()
                        }, 1000)
                      })
                      .catch(console.error)
                  },
                  fail: err => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '失败',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                })
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  title: '失败',
                  icon: 'none',
                  duration: 1000
                })
              }
            })
          }
        })
      }
    })
  },
  error(e) {
    console.log(e.detail)
  }
})